<template>
    <div>
        <div class="form-header">
            {{ type == "create" ? "添加sbu" : "修改sbu" }}
            <el-button type="success" @click="save" :loading="saveLoading"
                >保存</el-button
            >
        </div>
        <div class="gva-form-box">
            <div class="form-box">
                <el-form
                    :model="formData"
                    ref="elFormRef"
                    label-position="right"
                    :rules="rule"
                    label-width="120px"
                >
                    <el-form-item label="sbu组名:" prop="sbuName">
                        <el-input
                            v-model="formData.sbuName"
                            :clearable="true"
                            placeholder="请输入sbu组名"
                        />
                    </el-form-item>
                    <el-form-item label="组成员:" prop="member">
                        <el-select
                            v-model="formData.member"
                            placeholder="请选择成员"
                            style="width: 100%"
                            :clearable="true"
                            filterable
                            multiple
                            collapse-tags
                            collapse-tags-tooltip
                            :max-collapse-tags="3"
                        >
                            <el-option
                                v-for="(item, key) in memberListOptions"
                                :key="key"
                                :label="item.userName"
                                :value="item.userName"
                            />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="关联客户编号:" prop="customerNum">
                        <el-select
                            v-model="formData.customerNum"
                            placeholder="请选择客户"
                            style="width: 100%"
                            :clearable="true"
                            filterable
                            multiple
                            collapse-tags
                            collapse-tags-tooltip
                            :max-collapse-tags="3"
                        >
                            <el-option
                                v-for="(item, key) in customerListOptions"
                                :key="key"
                                :label="item.customerNum"
                                :value="item.customerNum"
                            />
                        </el-select>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
import { createSbuData, updateSbuData, findSbuData } from "@/api/confSbuData";

defineOptions({
    name: "sbuDataAdd",
});

// 自动获取字典
import { getDictFunc } from "@/utils/format";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ref, reactive } from "vue";
import { emitter } from "@/utils/bus.js";

import { getUserList } from "@/api/user";
import { getCustomerInfoList } from "@/api/confCustomerInfo";

const route = useRoute();
const router = useRouter();

const type = ref("");
const formData = ref({
    sbuName: "",
    member: [],
    customerNum: [],
});
const saveLoading = ref(false);

const memberListOptions = ref([]); // 人员列表
const customerListOptions = ref([]); // 客户列表

// 验证规则
const rule = reactive({
    sbuName: [{ required: true, message: "请输入sbu名称", trigger: "blur" }],
    member: [{ required: true, message: "请选择成员", trigger: "change" }],
    customerNum: [
        { required: true, message: "请选择客户编号", trigger: "change" },
    ],
});

const elFormRef = ref();

// 获取人员列表
const getMemberList = async () => {
    memberListOptions.value = [];
    const table = await getUserList({
        page: 1,
        pageSize: 9999,
    });
    if (table.code === 0) {
        memberListOptions.value = table.data.list;
    }
};

// 获取客户列表
const getCustomerList = async () => {
    const table = await getCustomerInfoList({
        page: 1,
        pageSize: 9999,
    });
    if (table.code === 0) {
        customerListOptions.value = table.data.list;
    }
};

// 初始化方法
const init = async () => {
    getMemberList();
    getCustomerList();

    // 建议通过url传参获取目标数据ID 调用 find方法进行查询数据操作 从而决定本页面是create还是update 以下为id作为url参数示例
    if (route.query.id) {
        const res = await findSbuData({ ID: route.query.id });
        if (res.code === 0) {
            formData.value = res.data.resbuData;
            formData.value["member"] = res.data.resbuData.member
                .split(",")
                .map((word) => {
                    const num = Number(word);
                    return Number.isNaN(num) ? word : num;
                });
            formData.value["customerNum"] =
                res.data.resbuData.customerNum.split(",");
            type.value = "update";
        }
    } else {
        type.value = "create";
    }
};

init();
// 保存按钮
const save = async () => {
    elFormRef.value?.validate(async (valid) => {
        if (!valid) return;
        let res;
        let submitData = {};
        let { sbuName, member, customerNum } = formData.value;
        Object.assign(submitData, formData.value);
        submitData["sbuName"] = sbuName;
        submitData["member"] = member.join(",");
        submitData["customerNum"] = customerNum.join(",");
        saveLoading.value = true;
        res = await updateSbuData(submitData);
        saveLoading.value = false;
        if (res.code === 0) {
            ElMessage({
                type: "success",
                message: "创建成功",
            });
            emitter.emit("closeThisPage", {
                path: "/layout/configureDatabase/sbuData",
            });
        }
    });
};

// 返回按钮
const back = () => {
    router.go(-1);
};
</script>

<style lang="scss" scoped>
.form-header {
    font-size: 22px;
    font-weight: 600;
    background: #fff;
    padding: 20px;
    border-bottom: 1px solid #ccc5;
    display: flex;
    justify-content: space-between;
}
.form-box {
    width: 45%;
    margin: 0 auto;
}
.form-footer {
    text-align: center;
}
</style>
